<?php
/**
 * Created by PhpStorm.
 * User: 50330
 * Date: 2019/4/15
 * Time: 14:33
 */

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers;
use function PHPSTORM_META\type;
use Qcloud\Sms\SmsSingleSender;
class Test extends Controller
{
    //表单验证
    public function add(Request $request){
        //是否是Post提交
        if($request->isMethod('post')){
            $this->validate($request,[
                //表单名称，规则，多个规则用中竖线|隔开
                'username'=>'required|max:4|min:2',
                'email'=>'required|email',
                'mobile'=> 'required|regex:/^1[34578]\d{9}$/',
                'pwd'=>'required|max:12|min:6|confirmed',
                'pwd_confirmation'=>'required',
//                'code'=>'required'
            ],[
                'username.required'=>'用户名不能为空',
                'username.max'=>'用户名不能超过4个字符',
                'username.min'=>'用户名不能少于2个字符',
                'email.required'=>'邮箱不能为空',
                'email.email'=>'邮箱不合法',
                'mobile.required'=>'手机号不能为空',
                'mobile.regex'=>'手机号不合法',
                'pwd.required'=>'密码不能为空',
                'pwd.max'=>'密码不能大于12位',
                'pwd.min'=>'密码不能小于6位',
                'pwd.confirmed'=>'两次密码不一致',
                'pwd_confirmation.required'=>'确认密码不能为空',
//                'code.required'=>'请输入验证码'
            ]);
            $user_info = $request->all();
//            dd($user_info);
            //验证用户是否已经存在
            $user_isexit=DB::select('select username from user where username = ?',[$user_info['username']]);
            if ($user_isexit){
                return json_encode(array('code'=>1,'info'=>'该用户名已经被注册'), JSON_UNESCAPED_UNICODE);
            }
            //验证邮箱是否被绑定
            $email_isexit=DB::select('select email from user where email = ?',[$user_info['email']]);
            if ($email_isexit){
                return json_encode(array('code'=>1,'info'=>'该邮箱已被绑定'), JSON_UNESCAPED_UNICODE);
            }
            //验证手机号是否被绑定
            $mobile_isexit=DB::select('select mobile from user where mobile = ?',[$user_info['mobile']]);
            if ($mobile_isexit){
                return json_encode(array('code'=>1,'info'=>'该手机号已被绑定'), JSON_UNESCAPED_UNICODE);
            }
            //验证验证码是否正确
//            $code = session()->get('code_info');
//            if ($user_info['code'] != $code){
//                return array('code'=>0,'info'=>'你输入的验证码有误');
//            }
            //加密密码,存入数据库
            $hashpwd = Hash::make($user_info['pwd']);
            $data = [$user_info['username'],$user_info['email'],$user_info['mobile'],$hashpwd,time()];
            $res = DB::insert('insert into user (username,email,mobile,password,createtime)values(?,?,?,?,?)',$data);
            if ($res){
//                return redirect('/log');
                return array('code'=>1,'info'=>'注册成功');
            }else{
                return array('code'=>0,'info'=>'注册失败');
            }
        }
    }

    /**
     * 发送短信验证码
     */
    public function sendMobile(Request $request)
    {
        //生成一个6位数字验证码
        $mobileCode = rand(000000,999999);
        $mobile = $request->input('mobile');
        //验证手机号是否正确
        preg_match('/^1[34578]\d{9}$/', $mobile, $match);

        if($match){
            //调用短信接口，发送短信
            $sms = $this->sendSms($mobile, $mobileCode);

            if($sms['result'] == 0){
                //把验证码放入session中，并记录失效时间
                session(['code_info'=>$mobileCode,'time'=>time()]);
//                session('code_info',['code'=>$mobileCode, 'mobile'=>$mobile, 'time'=>time() + 300]);
                return array('code'=>1, 'info'=>'验证码发送成功，5分钟内有效');
            }else{
                return array('code'=>0, 'info'=>'验证码发送失败');
            }
        }else{
            return array('code'=>0, 'info'=>'手机号有误');
        }
    }
    public function sendSms($phone, $code)
    {
        // 短信应用SDK AppID
//        $appid =1400170241; // 1400开头
        // 短信应用SDK AppKey
//        $appkey = "9ecace73ca78cfbcf1178e135c368a55";
        // 短信模板ID，需要在短信应用中申请
        $templateId = 245450;
        // 签名
        try {
            $ssender = new SmsSingleSender($appid, $appkey);
            $result = $ssender->send(0, "86", $phone,
                "【书生主页】您的验证码为".$code."，5分钟内有效。", "", "");
            $res = (array)$result;
            return json_decode($res[0], true);
        } catch(\Exception $e) {
            echo var_dump($e);
        }
    }

    //登陆
    public function login(Request $request){
        if ($request->isMethod('post')){
            //判断登陆方式
            $username = $request->input('username');
            $pwd = $request->input('pwd');
            // 判断用户是否存在,密码是否正确
            $res = DB::select('select * from user where username=?',[$username]);
            if ($res){
                $check=Hash::check($pwd, $res[0]->password);
                if ($check){
                    // 用户信息存到sission中
                    session(['user_info'=>$res]);
//                    dd(session()->all());
                    return array('code'=>1,'info'=>'成功');
                }else{
                    return array('code'=>0, 'info'=>'用户名或密码错误');
                }
            }else{
                return array('code'=>0, 'info'=>'用户不存在');
            }
        }
    }

    //退出登陆,清空session
    public function logout(Request $request){
        session(['user_info' => null]);
//        dd(session()->all());
        return redirect('/log');
    }


}